﻿
/*Author：Lary Pan(itolmqj123@gmail.com)
 *Date  ：2016/6/5
 *Tips  ：UI管理器
 * */
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class UIRecord
{
    public string path;             //ui的路径
    public UIBase uibase;           //
    public Action<UIBase> action;   //ui的打开后的事件
}

public class UIManager : ISingleton<UIManager>, IManager
{
    private readonly int DepthStep = 10;

    private List<UIRecord> uiList;
    private Stack<UIRecord> recordStack;
    private int currDepth = 0;


    public void Init()
    {
        uiList = new List<UIRecord>();
        recordStack = new Stack<global::UIRecord>();
    }

	public void DoDestroy()
    {
        uiList.Clear();
    }
  
    public void OpenUI(string path, Action<UIBase> _action = null)
    {

        foreach (var item in uiList)
        {
            if (item.path == path) return;
        }

        ResHelper.LoadLocalRes(path, obj =>
        {
            if (obj != null )
            {
              
                UIBase uiBase = ((GameObject)obj).GetComponent<UIBase>();

                //record
                UIRecord record = new global::UIRecord();
                record.action = _action;
                record.path = path;
                record.uibase = uiBase;
                recordStack.Push(record);
                //            if (!uiBase.keepDepth)
                //            {
                //                currDepth += DepthStep;
                //	//uiBase.PanelDepth = currDepth;
                //}
                if (!(uiBase is UILoading)) _AddToList(record);
                if (_action != null) _action(uiBase);
            }
        });
    }

    public void UIReview()
    {
        if (recordStack.Count > 0)
        {
            UIRecord record = recordStack.Pop();
            RemoveUI(record);
        }

        if (recordStack.Count > 0)
        {
            UIRecord record = recordStack.Pop();
            OpenUI(record.path, record.action);
        }
    }


    private void _AddToList(UIRecord uiRecord)
    {
        uiList.Add(uiRecord);
    }

    public void RemoveUI(UIRecord uiRocord)
    { 
        //if (!uiBase.keepDepth && uiBase.PanelDepth == currDepth)
        //{
        //    currDepth -= DepthStep;
        //}
        uiList.Remove(uiRocord);
        GameObject.Destroy(uiRocord.uibase.gameObject);
    }

    /// <summary>
    /// 操作所有界面，用于恢复
    /// </summary>
    /// <param name="isActive">是否显示</param>
    public void SetActiveAll(bool isActive)
    {
        uiList.ForEach(uiBase => uiBase.uibase.gameObject.SetActive(isActive));
    }
}
